﻿using Cysharp.Threading.Tasks;
using Net.Event;
using Net.Server;
using Net.Share;
using Net.System;
using Wordgames;
using WordGames.System;

namespace WordGames
{
    public class LoginService : TcpServer<ClientPeer>
    {
        protected override void OnStartupCompleted()
        {
            base.OnStartupCompleted();
            OnNetworkDataTraffic += (df) =>
            {
                Console.Title = $"Login {Port} {df}";
            };
        }

        protected override void OnReceiveDataHandler(ClientPeer client, IRpcModel model, ISegment segment)
        {
            switch ((ProtoType)model.Protocol)
            {
                case ProtoType.Register:
                    _ = Register(client, model.AsString, model.AsString);
                    break;
                case ProtoType.Login:
                    _ = Login(client, model.AsString, model.AsString);
                    break;
            }
        }

        private async UniTaskVoid Register(ClientPeer client, string account, string password)
        {
            var token = client.Token;
            var cache = ClusterSystem.DBCluster.GetCache(account);
            cache.Locking.Enter();
            var data = await ClusterSystem.DBCluster.QueryAsync<UserData>(account, $"account = '{account}'");
            int code = -1;
            if (data == null)
            {
                data = new UserData
                {
                    Account = account,
                    Password = password,
                    Level = 1,
                    Context = ClusterSystem.DBCluster.GetDBNode(account)
                };
                data.NewTableRow();
                code = 1;
            }
            cache.Locking.Exit();
            Response(client, ProtoType.Register, token, code);
        }

        private async UniTaskVoid Login(ClientPeer client, string account, string password)
        {
            var token = client.Token;
            var data = await ClusterSystem.DBCluster.QueryAsync<UserData>(account, $"account = '{account}'");
            if (data == null)
            {
                Response(client, ProtoType.Login, token, -1, null);
                return;
            }
            if (data.Password != password)
            {
                Response(client, ProtoType.Login, token, -2, null);
                return;
            }
            Response(client, ProtoType.Login, token, 1, data);
        }
    }
}
